package net.wang.concurrency.test.commonUnsafe;

import lombok.extern.slf4j.Slf4j;
import net.wang.concurrency.annoations.ThreadSafe;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;


@SuppressWarnings("ALL")
@ThreadSafe
@Slf4j
public class StringExample2 {

    public static int clientTotal = 5000;
    public static int threadTotal = 200;
    public static StringBuffer builder = new StringBuffer();

    @Test
    public void notThreadSafeTest() throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.info("exception : {}", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("size = {}", builder.length());
    }

    public void add() {
        builder.append("!");
    }

}
